package net.flydy.ywxcx.wxcloudrun.config;


import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 见 https://zhuanlan.zhihu.com/p/66789473
 */
@WebFilter(filterName = "CorsFilter ")
@Configuration
public class CorsFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        String originUrl = request.getHeader("origin");//请求的地址

        if (!StringUtils.isEmpty(originUrl)) {
            //自定义跨域域名检查
            boolean isAllow = checkAllow(originUrl);
            if (isAllow) {
                response.setHeader("Access-Control-Allow-Origin", originUrl);
            }
//            response.setHeader("Access-Control-Allow-Origin", "*");

            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
            response.setHeader("Access-Control-Max-Age", "1800");//30分钟
            response.setHeader("Access-Control-Allow-Headers", "x-requested-with, content-type, Yourflag");

            //对预请求单独处理
            String method = request.getMethod();
            if (method.equalsIgnoreCase("OPTIONS")) {
                response.setStatus(HttpServletResponse.SC_OK);
                return;
            }
        }
        filterChain.doFilter(request, response);
    }

    private boolean checkAllow(String originUrl) {
        return true;
    }
}